package stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author Hongliang Zhu
 * @create 2021-08-01 15:19
 */
public class Demo6 {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);

        System.out.println(list.stream().reduce((x, y) -> x + y).get());
        System.out.println(list.stream().reduce(Integer::sum).get());
        System.out.println(list.stream().reduce(0, Integer::sum));

        // 求乘积
        System.out.println(list.stream().reduce(1, (x, y) -> x * y));

        System.out.println(list.stream().reduce((x, y) -> x * y).get());

        // 求最大值

        List<Integer> list2 = Arrays.asList(-1,-5,-9);

        System.out.println(list2.stream().reduce((x, y) -> x > y ? x : y).get());
        System.out.println(list2.stream().reduce(Integer.MIN_VALUE, Integer::max));



//        案例二：求所有员工的工资之和和最高工资。

        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 24, "female", "New York"));
        personList.add(new Person("Owen", 9500, 25, "male", "New York"));
        personList.add(new Person("Alisa", 7900, 26, "female", "New York"));

// 求工资之和方式1：
        System.out.println(personList.stream().map(Person::getSalary).reduce(Integer::sum));

        // 求工资之和方式2：
        System.out.println(personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> null));

        // 求工资之和方式3：
        Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);

        // 最高工资
        System.out.println(personList.stream().map(Person::getSalary).reduce(Integer::max));

        // 求最高工资方式1：
        Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
                Integer::max);

        // 求最高工资方式2：
        Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
                (max1, max2) -> max1 > max2 ? max1 : max2);


    }
}
